package com.scedu.config;

import com.scedu.filter.JwtVerifyFilter;
import com.scedu.filter.JwtloginFilter;
import com.scedu.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;

@Configuration
@EnableWebSecurity
//在启动类上添加开启方法级的授权注解
@EnableGlobalMethodSecurity(securedEnabled =true )
//SpringSecurity配置类
public class SecurityConfig extends WebSecurityConfigurerAdapter {
//    1、配置用户来源
    @Autowired
    UserService userService;
    @Autowired
    JWTConfig jwtConfig;
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        /*
        <!--设置Spring Security认证用户信息的来源-->
        <security:authentication-manager>
            <security:authentication-provider>
                <security:user-service>
                    <security:user name="user" password="{noop}user"
                    authorities="ROLE_USER" />
                    <security:user name="admin" password="{noop}admin"
                    authorities="ROLE_ADMIN" />
                </security:user-service>
            </security:authentication-provider>
        </security:authentication-manager>
         */
//        auth.inMemoryAuthentication()
//                .withUser("user")
//                .password("{noop}123")
//                .roles("USER"); //注意这里不要加前缀
        auth.userDetailsService(userService).passwordEncoder(new BCryptPasswordEncoder());
    }

    protected void configure(HttpSecurity http) throws Exception {
        http
    //关闭跨站请求防护
                    .cors().and().csrf().disable()
    //允许不登陆就可以访问的方法，多个用逗号分隔
                    .authorizeRequests().antMatchers("/product").hasAnyRole("USER")
    //其他的需要授权后访问
                    .anyRequest().authenticated()
                    .and()
    //增加自定义认证过滤器
                    .addFilter(new JwtloginFilter(authenticationManager(), jwtConfig))
    //增加自定义验证认证过滤器
                    .addFilter(new JwtVerifyFilter(authenticationManager(), jwtConfig))
    // 前后端分离是无状态的，不用session了，直接禁用。
                    .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS);


    }
}
